<?php

namespace app\common\model;

use app\common\model\order\Order;
use app\common\model\user\Daydiviend;
use think\Db;
use think\Model;
use think\model\Collection;

/**
 * 会员余额日志模型
 */
class MoneyLog extends Model
{

    // 表名
    protected $name = 'user_money_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
        'createtime_text'
    ];
    // $last_week =  strtotime("last week Monday", $timestamp);
    // $last_month =  mktime(0, 0, 0, date('m') - 1, 1, date('Y'));

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    /**
     * 分红结算-月结
     * @Author xy
     * @Date 2023-12-07 17:27:17
     * @LastEditors xy
     * @LastEditTime Do not edit
     * @Description 
     */
    static function addDividend()
    {

        if (Billing::where('type', 'month_dividend')->where('key', date('Y-m'))->value('id')) {
            return false;
        }
        $all = User::sum('dividend');
        $last_month =  mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
        $to_month =  mktime(0, 0, 0, date('m'), 1, date('Y'));

        // $last_month =  mktime(0, 0, 0, date('m'), 1, date('Y'));
        // $to_month =  mktime(0, 0, 0, date('m')+1, 1, date('Y'));

        $order_money = Order::where('order_class', '1')->where('order_status', 'in', ['10', '20', '30', '40'])->where('paytime', 'between', [$last_month, $to_month])->sum('total_fee');
        $per = config('site.dividend_turnover_per') ?? 5;
        $has = bcdiv($order_money * $per, 100, 5);
        $users = User::where('dividend', '>', 0)->field('id,dividend,level_id')->select();
        foreach ($users as $key => $user) {
            User::money(bcdiv($user->dividend * $has, $all, 2), $user->id, '分红值结算', ['class' => 'dividend']);
            User::dividend(-$user->dividend, $user->id, date('m') . "月结算");
        }
        Billing::create([
            'data' => json_encode($users, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'type' => 'month_dividend',
            'key' => date('Y-m'),
            // 'billingtime'=>date('Y-m-d H:i:s'),
            // 'day' => date()
        ]);
        // User::update(['dividend' => 0]);
    }

    /**
     * 平级奖
     * @Author xy
     * @Date 2023-12-08 14:45:04
     * @LastEditors xy
     * @LastEditTime Do not edit
     * @Description 
     */
    static function addEqLevel($order)
    {

        if (Billing::where('type', 'eq_level')->where('key', date('Y-m'))->value('id')) {
            return false;
        }
        $last_month =  mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
        $to_month =  mktime(0, 0, 0, date('m'), 1, date('Y'));


        $users = Collection(User::where('level_id',  4)->field('id,team_tag,pid')->select())->toArray();
        $top_pids = [];
        foreach ($users as $key => $user) {
            $ids1 = explode(',', $user['team_tag']);
            $user['count'] = count($ids1);
            $user['ids'] = $ids1;
            if (array_key_exists($ids1[0], $top_pids)) {
                array_push($top_pids[$ids1[0]], $user);
            } else {
                $top_pids[$ids1[0]] = [$user];
            }
        }

        foreach ($top_pids as $id => $v) {

            $last_names = array_column($v, 'count');
            array_multisort($last_names, SORT_DESC, $v);
            $a1 = array_reverse($v[0]['ids']);
            $str = implode(',', $a1);
            $parents = User::where("id", 'in', $a1)->where('level_id', 4)->orderRaw("field(id,$str)")->select();
            if (count($parents) > 1) {
                $i = 0;
                $uids = User::where('find_in_set(:id,team_tag)', ['id' => $v[0]['id']])->where('id', '!=', $v[0]['id'])->column('id');
                $order_money = Order::where('user_id', 'in', $uids)->where('order_class', '1')->where('order_status', 'in', ['10', '20', '30', '40'])->where('paytime', 'between', [$last_month, $to_month])->sum('total_fee');

                foreach ($parents as $user) {
                    if ($i == 1) {
                        User::money(bcdiv($order_money * config('site.eq_level_rate1'), 100), $user->id, '佣金补贴1');
                    } elseif ($i == 2) {
                        User::money(bcdiv($order_money * config('site.eq_level_rate2'), 100), $user->id, '佣金补贴2');
                    }
                    $i++;
                }
            }
        }

        Billing::create([
            'data' => json_encode($users, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'type' => 'eq_level',
            'key' => date('Y-m'),
            // 'billingtime'=>date('Y-m-d H:i:s'),
            // 'day' => date()
        ]);
    }


    /**
     * 加权分红-月结
     */
    static function addjqDividend()
    {

        if (Billing::where('type', 'jq_dividend')->where('key', date('Y-m'))->value('id')) {
            return false;
        }
        $all = User::sum('dividend');
        $last_month =  mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
        $to_month =  mktime(0, 0, 0, date('m'), 1, date('Y'));

        // $last_month =  mktime(0, 0, 0, date('m'), 1, date('Y'));
        // $to_month =  mktime(0, 0, 0, date('m') + 1, 1, date('Y'));

        $order_money = Order::where('order_class', '1')->where('order_status', 'in', ['10', '20', '30', '40'])->where('paytime', 'between', [$last_month, $to_month])->sum('total_fee');
        $per = config('site.ds_add_dividend') ?? 2;
        $has = bcdiv($order_money * $per, 100, 5);

        //董事

        $ds =  User::where('level_id', '>=', 5)->field('id,level_id,avatar,nickname,mobile')->select();
        $count = count($ds);
        if ($count) {
            foreach ($ds as $key => $user) {
                User::money(bcdiv($has, $count, 2), $user->id, '董事分红结算', ['class' => 'dividend']);
            }
        }
        // //区县
        // $qx =  User::where('level_id', 6)->select();
        // $count = count($qx);
        // if ($count) {
        //     foreach ($qx as $key => $user) {
        //         User::money(bcdiv($has, $count, 2), $user->id, '董事分红结算');
        //     }
        // }

        // //市级
        // $sj =  User::where('level_id', 7)->select();
        // $count = count($sj);
        // if ($count) {
        //     foreach ($sj as $key => $user) {
        //         User::money(bcdiv($has, $count, 2), $user->id, '董事分红结算');
        //     }
        // }


        // //创始团队
        // $cs =  User::where('level_id', 8)->select();
        // $count = count($cs);
        // if ($count) {
        //     foreach ($cs as $key => $user) {
        //         User::money(bcdiv($has, $count, 2), $user->id, '董事分红结算');
        //     }
        // }
        Billing::create([
            'data' => json_encode(Collection($ds)->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'type' => 'jq_dividend',
            'key' => date('Y-m'),
            // 'billingtime'=>date('Y-m-d H:i:s'),
            // 'day' => date()
        ]);
    }


    /**
     * 周分红
     */
    static function addWeekDividend()
    {
        if (Billing::where('type', 'week_dividend')->where('key', date('YW'))->value('id')) {
            return false;
        }
        $starttime =  strtotime("last week Monday");
        $today = strtotime(date('Y-m-d'));
        $weekday = date('w') == 0 ? 7 : date('w');
        // $endtime = $today - ($weekday - 1) * 3600 * 24;
        $endtime = $starttime + 7 * 86400;


        // $endtime = strtotime(' monday -6 day', time());

        // var_dump($starttime);
        // var_dump($endtime);

        $order_money = Order::where('order_class', '1')->where('order_status', 'in', ['10', '20', '30', '40'])->where('paytime', 'between', [$starttime, $endtime])->sum('total_fee');


        $per = config('site.week_dividend_turnover_per') ?? 5;
        $has = bcdiv($order_money * $per, 100, 5);
        // var_dump($has);
        $data = [];
        if ($has > 0) {

            // return false;

            //分红股东
            $levels = [4, 5, 6, 7, 8];
            $all = User::where('level_id', 'in', $levels)->count();
            $total_team_week_consume = User::where('level_id', 'in', $levels)->sum('team_week_consume');

            foreach ($levels as $level) {
                $users = User::where('level_id', $level)->select();
                // var_dump($all);
                if ($all) {
                    foreach ($users as $key => $user) {
                        array_push($data, [
                            'user_id' => $user->id,
                            'total_dividend_commission' => $user->total_dividend_commission,
                            'consume' => $user->consume,
                            'team_week_consume' => $user->team_week_consume,
                            'level_id' => $user->level_id,
                            'is_formal_goudong' => $user->is_formal_goudong,
                            'level4_sq' => $user->level4_sq
                        ]);
                        if ($level == 4 && !$user->is_formal_goudong) {

                            if ($user->level4_sq < 94) {
                                $t = config('site.level4_week_limit1') ?? 10000;
                            } 
                            // elseif ($user->level4_sq < 301) {
                            //     $t = config('site.level4_week_limit2') ?? 2000;
                            // }
                            // elseif ($user->level4_sq < 1315) {
                            //     $t = config('site.level4_week_limit3') ?? 3000;
                            // }
                            else {
                                $t = 0;
                            }
                            if ($user->total_dividend_commission < $t) {

                                User::money(bcdiv(0.33 * $has, $all, 2), $user->id, '周分红', ['class' => 'week_dividend']);

                                // User::money(bcdiv(0.67 * $has * $user->team_week_consume, $total_team_week_consume, 2), $user->id, '周业绩分红', ['order_sn' => $user->team_week_consume, 'class' => 'dividend']);
                            } else {
                                // User::money(bcdiv(0.67 * $has * $user->team_week_consume, $total_team_week_consume, 2), $user->id, '周业绩分红', ['order_sn' => $user->team_week_consume, 'class' => 'dividend']);
                            }
                        } else {
                            if ($level == 5 && $user->level5_sq > 1314) {
                                // User::money(bcdiv(0.67 * $has * $user->team_week_consume, $total_team_week_consume, 2), $user->id, '周业绩分红', ['order_sn' => $user->team_week_consume, 'class' => 'dividend']);
                            } else {
                                User::money(bcdiv(0.33 * $has, $all, 2), $user->id, '周分红', ['class' => 'week_dividend']);

                                // User::money(bcdiv(0.67 * $has * $user->team_week_consume, $total_team_week_consume, 2), $user->id, '周业绩分红', ['order_sn' => $user->team_week_consume, 'class' => 'dividend']);
                            }
                        }
                    }
                }
            }
        }
        // (new User)->saveAll(['team_week_consume' => 0]);
        // die;
        $sql = "update fa_user set team_week_consume=0";
        Db::execute($sql);

        Billing::create([
            'data' => json_encode(['total' => $order_money, 'list' => $data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'type' => 'week_dividend',
            'key' => date('YW'),
            // 'billingtime'=>date('Y-m-d H:i:s'),
            // 'day' => date()
        ]);
    }

    /**
     * 日分红
     */
    static function addDayDividend()
    {
        if (Billing::where('type', 'day_dividend')->where('key', date('Y-m-d'))->value('id')) {
            return false;
        }
        $starttime =  strtotime(date('Y-m-d', strtotime('-1 day')));
        $endtime =  strtotime(date('Y-m-d 00:00:00'));


        // $starttime =  strtotime(date('Y-m-d 00:00:00'));
        // $endtime =  strtotime(date('Y-m-d 23:59:59'));

        $order_money = Order::where('order_class', '1')->where('order_status', 'in', ['10', '20', '30', '40'])->where('paytime', 'between', [$starttime, $endtime])->sum('total_fee');


        $per1 = config('site.day_dividend_turnover_per') ?? 5;
        $has = bcdiv($order_money * $per1, 100, 5);

        //分红股东
        $levels = [4, 5, 6, 7, 8];
        // foreach ($levels as $level) {
        // $users = User::where('level_id', 'in', $levels)->where('today_share_vip', '>', 0)->select();
        $users = User::where('level_id', 'in', $levels)->where('today_share_consume', '>', 0)->select();

        $all = count($users);
        // $total_per = floor($order_money / config('site.day_dividend_consume_per'));
        $total_per = 0;
        $to_send = [];

        $rates = Daydiviend::order('num desc')->select();
        if ($all) {
            foreach ($users as $key => $user) {

                if ($user->today_share_consume >= config('site.day_dividend_consume_per')) {
                    $per = floor($user->today_share_consume / config('site.day_dividend_consume_per'));
                    $total_per += $per;
                    array_push($to_send, ['user_id' => $user->id, 'per' => $per]);
                    // User::money(bcdiv($has * $per, $total_per, 2), $user->id, '日分红结算', ['class' => 'dividend']);
                }

                // }
                // }
            }

            foreach ($to_send as $key => $user) {
                User::money(bcdiv($has * $user['per'], $total_per, 2), $user['user_id'], '日分红结算', ['class' => 'dividend']);
            }
        }
        // }

        // User::update(['today_share_vip' => 0]);
        $sql = "update fa_user set today_share_vip=0,today_share_consume=0";
        Db::execute($sql);
        Billing::create([
            'data' => json_encode($to_send, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'type' => 'day_dividend',
            'key' => date('Y-m-d'),
            // 'billingtime'=>date('Y-m-d H:i:s'),
            // 'day' => date()
        ]);
    }


    /**
     * 
     */
    static function getDayRate($rates, $num)
    {
        foreach ($rates as $key => $v) {
            if ($num > $v->num) {
                return $v;
            }
        }
        // return 0;
    }
    /**
     * 代理佣金极差
     */
    static function addAgentPrice($order)
    {
        $u = $order->user;
        $ids = explode(',', $u->team_tag);
        // array_pop($ids);
        $ids = array_reverse($ids);
        // var_dump()
        $str = implode(',', $ids);
        if (!$str) {
            return;
        }
        $parents = User::where("id", 'in', $ids)->where('level_id', '>=', 3)->orderRaw("field(id,{$str})")->select();
        if ($parents) {
            $current_level = 0;
            $last_rate = 0;

            $eq_level = 0;
            foreach ($parents as $key => $user) {
                if($user->level_id==5){
                    $user->level_id = 4;
                }
                if ($user->level_id > $current_level) {
                    $current_level = $user->level_id;
                    if ($current_level == 5) {
                        $current_level = 4;
                    }
                    if ($current_level == 4) {
                        $eq_level = 1;
                    }


                    if ($user->userlevel->agent_rate ?? 0) {

                        if ($user->userlevel->agent_rate > $last_rate) {
                            $dev = $user->userlevel->agent_rate - $last_rate;
                            // echo  $user->id."::".bcdiv($dev * $order->total_fee, 100, 2);
                            // echo "<br>";
                            if ($order->user_id != $user->id) {
                                User::money(bcdiv($dev * $order->total_fee, 100, 2), $user->id, '利差佣金', ['order_sn' => $order->sn, 'class' => 'dividend']);
                            }
                        }
                    }
                    $last_rate = $user->userlevel->agent_rate ?? $last_rate;
                } elseif (($user->level_id == 4 || $user->level_id == 5) && $eq_level == 1) {
                    // 平级佣金
                    User::money(bcdiv($order->total_fee * config('site.eq_level_rate1'), 100, 2), $user->id, '贡献佣金', ['order_sn' => $order->sn, 'class' => 'dividend']);
                    $eq_level = 2;
                } elseif (($user->level_id == 4 || $user->level_id == 5) && $eq_level == 2) {
                    // 平级佣金
                    // User::money(bcdiv($order->total_fee * config('site.eq_level_rate2'), 100, 2), $user->id, '佣金补贴2', ['order_sn' => $order->sn, 'class' => 'dividend']);
                    $eq_level = 3;
                }
            }
        }
    }


    //区域代理结算
    static function addAreaAgent($order)
    {

        if ($order->order_type == '1') {
            $province = self::getArea($order->province ?? '', 1);

            $city = self::getArea($order->city ?? '', 2, $province->id ?? 0);

            $area = self::getArea($order->area ?? '', 3, $city->id ?? 0);
        } else {
            $pick = Pick::get(1);
            $ids = explode(',', $pick->city);
            // if ($province) {
            //     //区域
            //     $Areaid = $province->pid;
            //     $has[$Areaid] = ($has[$Areaid] ?? 0) + $order->total_fee;
            //     $has[$province->id] = ($has[$province->id] ?? 0) + $order->total_fee;
            // }
            $city = Area::get($ids[1] ?? 0);

            $area = Area::get($ids[2] ?? 0);
        }

        $rate = 0;
        if ($area) {
            // 区县代理
            $has = User::where('agent_area_id', $area->id)->where('level_id', 6)->find();

            if ($has) {
                $rate = config('site.area_agent_rate');
                User::money(bcdiv($rate * $order->total_fee, 100, 2), $has->id, '区县代理', ['order_sn' => $order->sn, 'class' => 'dividend']);
            }
            // $has[$area->id] = ($has[$area->id] ?? 0) + $order->total_fee;
        }

        if ($city) {
            // 市级代理
            $has = User::where('agent_area_id', $city->id)->where('level_id', 7)->find();

            if ($has) {
                $crate = floatval(config('site.city_agent_rate')) - $rate;
                User::money(bcdiv($crate * $order->total_fee, 100, 2), $has->id, '市级代理', ['order_sn' => $order->sn, 'class' => 'dividend']);
            }
            // $has[$city->id] = ($has[$city->id] ?? 0) + $order->total_fee;
        }
    }



    /**
     * 累计分红值
     */
    public static function addUserDividend($order)
    {
        // $user = $order->user;

        // $order->user->
        if ($order->user->level_id) {
            User::where('id', $order->user_id)->inc('consume', $order->total_fee)->inc('order_num', 1)->update();
            // User::dividend($order->total_fee, $order->user_id, '购买商品');
        } else {
            User::where('id', $order->user_id)->inc('consume', $order->total_fee)->inc('order_num', 1)->update();
        }
        if (isset($order->user->userlevel->id) && $order->user->level_id >= 2) {
        } else {
            if ($order->user->pid) {
                $puser = User::get($order->user->pid);
                if ($puser) {
                    //直推

                    $puser->today_share_consume += $order->total_fee;
                    $puser->save();
                    if (isset($puser->userlevel->id) && $puser->level_id >= 2) {
                        // User::dividend(bcdiv($puser->userlevel->dividend_rate1 * $order->total_fee, 100, 2), $puser->id, '直推分销');
                        User::money(bcdiv(30 * $order->total_fee, 100, 2), $puser->id, '分享佣金', ['order_sn' => $order->sn, 'class' => 'dividend']);

                        // $puser->dividend += bcdiv($puser->userlevel->dividend_rate1 * $order->total_fee, 100, 2);
                        // $puser->save();
                    }
                    // if ($puser->pid) {
                    //     $ppuser = User::get($puser->pid);
                    //     if ($ppuser) {
                    //         //间推
                    //         if (isset($ppuser->userlevel->id) && $ppuser->userlevel->dividend_rate2) {
                    //             User::dividend(bcdiv($ppuser->userlevel->dividend_rate2 * $order->total_fee, 100, 2), $ppuser->id, '间推分销');

                    //             // $ppuser->dividend += bcdiv($ppuser->userlevel->dividend_rate2 * $order->total_fee, 100, 2);
                    //             // $ppuser->save();
                    //         }
                    //     }
                    // }
                }
            }
        }
    }

    /**
     * 获取区域ID
     * @Author xy
     * @Date 2023-07-27 10:51:06
     * @LastEditors xy
     * @LastEditTime Do not edit
     * @Description 
     * @param {*} $name
     * @param {*} $level
     */
    public static function getArea($name, $level = 1, $pid = 0)
    {
        if ($pid) {
            if ($name == '市中区') {
                $province = Area::where('name', $name)->where('level', $level)->where('pid', $pid)->find();
            } else {
                $province = Area::where('shortname', 'like', str_replace(['省', '市', '自治区', '特别行政区', '区', '县'], '', $name) . '%')->where('level', $level)->where('pid', $pid)->find();
            }
        } else {
            $province = Area::where('shortname', str_replace(['省', '市', '自治区', '特别行政区', '区', '县'], '', $name))->where('level', $level)->find();
        }
        return $province;
    }
}
